package com.block.sms.service.send;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;
import com.block.common.constant.AppRspCodeConstant;
import com.block.db.entity.SmsConfigInfo;
import com.block.db.entity.SmsTemplate;
import com.block.sms.dto.SmsBalanceDTO;
import com.block.sms.dto.SmsResultDTO;
import com.block.sms.service.ISmsSendService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class AliSmsSendServiceImpl implements ISmsSendService {

    @Override
    public SmsResultDTO sendSms(String mobile, String outId, SmsTemplate smsTemplate, SmsConfigInfo smsConfigInfo, JSONObject codeJson) {

        SmsResultDTO  resultDTO = new SmsResultDTO();
        try {
            Config config = new Config()
                    // 您的 AccessKey ID
                    .setAccessKeyId(smsConfigInfo.getAccount())
                    .setEndpoint(smsConfigInfo.getEndpoint())
                    // 您的 AccessKey Secret
                    .setAccessKeySecret(smsConfigInfo.getSecret());

            com.aliyun.dysmsapi20170525.Client client = new com.aliyun.dysmsapi20170525.Client(config);

            SendSmsRequest sendSmsRequest = new SendSmsRequest()
                    .setSignName(smsTemplate.getSmsSign())
                    .setTemplateCode(smsTemplate.getTemplateId())
                    .setPhoneNumbers(mobile)
                    .setOutId(outId)
                    .setTemplateParam(codeJson.toJSONString());
            RuntimeOptions runtime = new RuntimeOptions();

            // 复制代码运行请自行打印 API 的返回值
            SendSmsResponse sendSmsResponse = client.sendSmsWithOptions(sendSmsRequest, runtime);
            log.info("【阿里云短信服务】发送结束【request】{}【response】{}【mobile】{}【code】{}",
                    JSON.toJSONString(sendSmsRequest),JSON.toJSONString(sendSmsResponse), mobile, codeJson.toJSONString());

            if (Integer.valueOf(200).equals(sendSmsResponse.getStatusCode())){
                resultDTO.setCode(AppRspCodeConstant.SUCCESS);
                resultDTO.setHttpStatus(String.valueOf(sendSmsResponse.getStatusCode()));
                resultDTO.setRequestId(outId);
                resultDTO.setMessage(sendSmsResponse.getBody().getMessage());
                return resultDTO;
            }
        } catch (Exception exception) {
            log.error(String.format("【阿里云短信服务】发送发生异常【mobile】%s【code】%s", mobile, codeJson.toJSONString()), exception);
        }

        resultDTO.setCode(AppRspCodeConstant.OPERATION_FAILURE);
        return resultDTO;
    }

    @Override
    public SmsBalanceDTO queryBalanceInfo(SmsConfigInfo smsConfigInfo) {
        return null;
    }

}
